<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CateController extends Controller
{
	//顶级分类列表
    public function getIndex(Request $request)
    {
    	if($request->input('keywords')){
    		$cate = DB::table('cate')
    			->where('catename','like','%'.$request->input('keywords').'%')
    			->paginate(5);
    	}else{
        	$cate = DB::table('cate')
    			->paginate(5);
    	}
    	$data = $request->all();
    	// dd($cate);
    	return view('admin.cate.index',['cate'=>$cate,'data'=>$data]);
    }
    //添加分类
    public function getAdd()
    {
    	return view('admin.cate.add');
    }
	//执行添加
	public function postInsert(Request $request)
	{
		$catename = $request->input('catename');
		$data['date'] = date('Y-m-d H:i:s',time());
		$data['catename'] = $catename;
		if($catename == ''){
			return back();
		}
		// 执行
		$res = DB::table('cate')->insert($data);
		if($res){
			return redirect('/admin/cate/index')->with('success','添加成功');
		}else{
			return back()->with('error','添加失败');
		}
	}
	//删除
	public function getDelete($id)
	{
		$res = DB::table('cate')->where('id',$id)->count();
		if(!$res){
			// return back();
		}
		$r = DB::table('cate')->where('id',$id)->delete();
		if($r){
			return back()->with('success','删除成功');
		}else{
			return back()->with('error','删除失败');
		}
	}
	//修改
	public function getEdit($id)
	{
		$cates = DB::table('cate')->where('id',$id)->first();
		return view('admin.cate.edit',['cates'=>$cates]);
	}
	//执行修改
	public function postUpdate(Request $request)
	{
		$data['id'] = $request->input('id');
		$catename = $request->input('catename');
		$data['catename'] = $catename;
		if($catename == ''){
			return back()->withInput();
		}

		$r = DB::table('cate')->where('id',$data['id'])->update($data);
		if($r){
			return redirect('admin/cate/index')->with('success','分类修改成功');
		}else{
			return back()->with('error','分类修改失败');
		}
	}
}
